import tkinter as tk
from tkinter import scrolledtext, filedialog, messagebox
import SparkApi

class ChatApp:
    def __init__(self, master):
        self.master = master
        master.title("郑恺-星火大模型UI界面")
        # 设置背景色
        bg_color = "#f0f0f0"
        master.configure(bg=bg_color)

        # 对话框文本框
        self.dialog_text = scrolledtext.ScrolledText(
            self.master, wrap=tk.WORD, width=50, height=20, font=("Microsoft YaHei UI", 12), bg="white", fg="black"
        )
        self.dialog_text = scrolledtext.ScrolledText(
            self.master, wrap=tk.WORD, width=50, height=20, font=("Microsoft YaHei UI", 12)
        )
        self.dialog_text.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
        self.dialog_text.grid_propagate(False)  # 阻止自动调整大小

        self.label_input = tk.Label(self.master, text="请您在下方输入:", font=("Microsoft YaHei UI", 12))
        self.label_input.grid(row=1, column=0, padx=3, pady=3, sticky="w")

        input_frame = tk.Frame(master)
        input_frame.grid(row=2, column=0, pady=10, sticky="nsew")
        input_frame.grid_columnconfigure(0, weight=3)

        self.input_entry = tk.Entry(
            input_frame, bd=2, relief=tk.GROOVE, font=("Microsoft YaHei UI", 12),
            borderwidth=4, highlightthickness=1, width=20
        )
        self.input_entry.grid(row=0, column=0, padx=10, pady=10, sticky="nsew")
        self.input_entry.grid_propagate(False)  # 阻止自动调整大小
        self.input_entry.bind("<Return>", self.send_on_enter)

        button_frame = tk.Frame(master)
        button_frame.grid(row=3, column=0, pady=10, sticky="nsew")

        self.send_button = tk.Button(button_frame, text="发送", command=self.send_message,
                                     font=("Microsoft YaHei UI", 12))
        self.send_button.grid(row=0, column=0, padx=5, sticky="nsew")

        self.file_button = tk.Button(button_frame, text="选择文本", command=self.load_file,
                                     font=("Microsoft YaHei UI", 12))
        self.file_button.grid(row=0, column=1, padx=5, sticky="nsew")

        self.save_button = tk.Button(
            button_frame, text="保存对话内容", command=self.save_to_text, font=("Microsoft YaHei UI", 12)
        )
        self.save_button.grid(row=0, column=2, padx=5, sticky="nsew")

        button_frame.grid_columnconfigure(0, weight=1)
        button_frame.grid_columnconfigure(1, weight=1)
        button_frame.grid_columnconfigure(2, weight=1)

        master.grid_rowconfigure(0, weight=1)
        master.grid_rowconfigure(1, weight=0)
        master.grid_rowconfigure(3, weight=1)
        master.grid_columnconfigure(0, weight=1)

        initial_text = "提前告诉星火大模型的内容，让其更关注你问的方向。"
        # sparkAPI(initial_text)   # 如果要提前送内容给模型，请取消注释
        self.dialog_text.insert(tk.END,
                                "你好！作者：“郑恺”！\n\n")

    def send_on_enter(self, event):
        self.send_message()

    def send_message(self):
        user_input = self.input_entry.get()
        if user_input.strip():
            assistant_response = sparkAPI(user_input)
            self.dialog_text.insert(tk.END, f"我: {user_input}\n")
            self.dialog_text.insert(tk.END, f"大佬: {assistant_response}\n")
            self.input_entry.delete(0, tk.END)
            self.dialog_text.see(tk.END)
        else:
            messagebox.showinfo("提示", "请输入消息！")

    def load_file(self):
        file_path = filedialog.askopenfilename(filetypes=[("Text files", "*.txt"), ("All files", "*.*")])
        if file_path:
            with open(file_path, 'r', encoding='utf-8') as file:
                content = file.read()
                self.input_entry.insert(tk.END, content)

    def save_to_text(self):
        content = self.dialog_text.get("1.0", tk.END)
        file_path = filedialog.asksaveasfilename(
            defaultextension=".txt", filetypes=[("Text files", "*.txt"), ("All files", "*.*")]
        )
        if file_path:
            with open(file_path, 'w', encoding='utf-8') as file:
                file.write(content)
            messagebox.showinfo("保存成功", "对话内容已保存为文本文件！")


def sparkAPI(input_text):
    text.clear()
    questions = checklen(getText("user", input_text))
    SparkApi.answer = ""
    SparkApi.main(appid, api_key, api_secret, Spark_url, domain, questions)
    assistant_answer = SparkApi.answer
    text.append({"role": "assistant", "content": assistant_answer})
    return assistant_answer


def getText(role, content):
    jsoncon = {"role": role, "content": content}
    text.append(jsoncon)
    return text


def getlength(text):
    length = 0
    for content in text:
        temp = content["content"]
        leng = len(temp)
        length += leng
    return length


def checklen(text):
    while getlength(text) > 8000:
        del text[0]
    return text


if __name__ == "__main__":
    appid = "64ff9ae4"
    api_secret = "ODY3MzNiZThmOGJmMTVkZjk4ZDVhYzk5"
    api_key = "fc586c03af9c4810a198faa3fd3d3214"
    domain = "lite"
    Spark_url = "wss://spark-api.xf-yun.com/v1.1/chat"

    text = []

    root = tk.Tk()
    root.geometry("800x750")
    chat_app = ChatApp(root)
    root.mainloop()

